/*
 *  Copyright (C) 2004 Cidero, Inc.
 *
 *  Permission is hereby granted to any person obtaining a copy of 
 *  this software to use, copy, modify, merge, publish, and distribute
 *  the software for any non-commercial purpose, subject to the
 *  following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY IN CONNECTION WITH THE SOFTWARE.
 * 
 *  File: $RCSfile: StatusMonitorThread.java,v $
 *
 */

package com.cidero.bridge.audiotron;

import java.util.logging.Logger;

/**
 * Thread to periodically get the Audiotron status and update the 
 * ATron status model. The AVTransport and RenderingControl services
 * are observers of the status model, generating UPnP LastChange events
 * as needed.
 *
 * Monitoring the ATron status allows changes made by non-UPnP means
 * (front panel controls and remote control) to be picked up and
 * transmitted to UPnP control points
 */
public class StatusMonitorThread implements Runnable
{
  private static Logger logger = 
    Logger.getLogger("com.cidero.bridge.audiotron");

  private final static int STATUS_REQUEST_TIMEOUT = 5000;

  ATronMediaRenderer mediaRenderer;
  int monitorPeriodMillisec;  

  /**
   * Constructor
   *
   * @param  asyncCmd                Asynchronous command queue
   * @param  atronStatusModel        ATron status object (Observable)
   * @param  monitorPeriodMillisec   How often to get ATron status
   */
  public StatusMonitorThread( ATronMediaRenderer mediaRenderer,
                              int monitorPeriodMillisec )
  {
    this.mediaRenderer = mediaRenderer;
    this.monitorPeriodMillisec = monitorPeriodMillisec;
  }
  
  private Thread monitorThread = null;  // for clean shutdown via stop()
  
  public void start()
  {
    monitorThread = new Thread( this );
    monitorThread.start();
  }
  
  public void stop()
  {
    monitorThread = null;
  }
  
  public void run()
  {
    logger.fine("StatusMonitorThread: Running...");

    Thread thisThread = Thread.currentThread();

    while( monitorThread == thisThread )
    {
      // logger.fine( "AsyncCommThread: Timeout waiting for cmd: " );        
      mediaRenderer.getRendererState();

      try {
        Thread.sleep( monitorPeriodMillisec ); 
      } catch( InterruptedException e ) {
      }
    }

    logger.fine( "async thread shutting down... " );        
  }

}

